package com.ruoyi.common.utils.msg.dto.req;

import lombok.Data;
import lombok.ToString;

import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

@Data
@ToString
public class FrameReqBodyElement {

    // 标识符引导符
    private String typeCode;
    // 数据字节数
    private Integer dataSize;
    // 小数位数
    private Integer decimalSize;
    // 原始数据
    private String originalData;
    // 实际值
    private String val;

    public FrameReqBodyElement(String typeCode, Integer dataSize, Integer decimalSize, String originalData) {
        this.typeCode = typeCode;
        this.dataSize = dataSize;
        this.decimalSize = decimalSize;
        this.originalData = originalData;
        try {
            val = calDoubleVal();
        } catch (Exception e) {
            // ignore
        }
    }

    public String calDoubleVal() {
        if ("f5".equals(typeCode.toString())) {
            List<String> decimalStringList = IntStream.range(0, originalData.length() / 4)
                .mapToObj(i -> originalData.substring(i * 4, i * 4 + 4))
                .map(hexPair -> Integer.parseInt(hexPair, 16)*0.01)
                .map(String::valueOf)
                .collect(Collectors.toList());
            // 将 List<String> 拼接成一个单一的字符串
            String concatenatedString = String.join(",", decimalStringList);
            // 将拼接后的字符串转换为 Double
            return concatenatedString;
        } else if ("f4".equals(typeCode.toString())) {
            List<String> decimalStringList = IntStream.range(0, originalData.length() / 2)
                .mapToObj(i -> originalData.substring(i * 2 , i * 2 + 2))
                .map(hexPair -> Integer.parseInt(hexPair, 16)*0.01)
                .map(String::valueOf)
                .collect(Collectors.toList());
            // 将 List<String> 拼接成一个单一的字符串
            String concatenatedString = String.join(",", decimalStringList);
            // 将拼接后的字符串转换为 Double
            return concatenatedString;
        } else {
            return String.valueOf(Double.parseDouble(new  StringBuffer(originalData).insert(dataSize * 2 - decimalSize, ".").toString()));
        }
        // 插入小数点并转换为双精度类型

    }
}
